const { Controller } = require('egg');

function toInt(str) {
    if (typeof str === 'number') return str;
    if (!str) return str;
    return parseInt(str, 10) || 0;
}

class UsersController extends Controller {
    async index() {
        const { ctx } = this;
        const query = {
            limit: toInt(ctx.query.limit),
            offest: toInt(ctx.query.offset),
        }
        ctx.responseData(await ctx.model.Users.findAll(query), "success", 0)
        // ctx.body = ;
    }
    async show() {
        const { ctx } = this;
        ctx.responseData(await ctx.model.Users.findByPk(toInt(ctx.params.id)), "success", 0)
    }

    async create() {
        const { ctx } = this;
        const { name, phone } = ctx.request.body;
        const user = await ctx.model.Users.create({ username: name, phone: phone, password: phone });
        ctx.responseData(user, "success", 1)
    }

    async update() {
        const { ctx } = this;
        const id = toInt(ctx.params.id);
        const user = await ctx.model.Users.findByPk(id);
        if (!user) {
            ctx.status = 404 + "查无此数据";
            return
        }

        const { name, phone } = ctx.request.body;
        await user.update({ name, phone });
        // ctx.body = user;
        ctx.responseData(user, "success", 1)
    }

    async destroy() {
        const { ctx } = this;
        const id = toInt(ctx.params.id);
        console.log("id", id)
        const user = await ctx.model.Users.findByPk(id);
        if (!user) {
            ctx.status = 404;
            return
        }

        await user.destroy();
        // ctx.status = 200;
        ctx.responseData({}, "success", 0)

    }


}

module.exports = UsersController;